package cn.wk.pay.service.impl;

import cn.wk.basic.config.AlipayConfig;
import cn.wk.basic.constant.ConstantPethome;
import cn.wk.basic.constant.PayConstant;
import cn.wk.basic.service.impl.BaseServiceImpl;
import cn.wk.order.domain.ProductOrder;
import cn.wk.order.mapper.ProductOrderMapper;
import cn.wk.org.domain.Shop;
import cn.wk.org.service.IShopService;
import cn.wk.pay.domain.AlipayInfo;
import cn.wk.pay.domain.PayBill;
import cn.wk.pay.mapper.AlipayInfoMapper;
import cn.wk.pay.mapper.PayBillMapper;
import cn.wk.pay.service.IPayBillService;
import cn.wk.quartz.service.IQuartzService;
import cn.wk.quartz.util.QuartzUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class PayBillServiceImpl extends BaseServiceImpl<PayBill> implements IPayBillService {
    @Autowired
    private AlipayInfoMapper alipayInfoMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private IQuartzService quartzService;
    @Override
    @Transactional
    public String goBuy(ProductOrder productOrder){
        try {
            //根据productOrder中的shopid去alipay中查询appid
            AlipayInfo alipayInfo = alipayInfoMapper.findByShopId(productOrder.getShop().getId());

            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, alipayInfo.getAppid(), alipayInfo.getMerchant_private_key(), "json", AlipayConfig.charset, alipayInfo.getAlipay_public_key(), AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = productOrder.getOrderSn();
            //付款金额，必填
            String total_amount = productOrder.getPrice().toString();
            //订单名称，必填
            String subject = productOrder.getDigest();
            //商品描述，可空
            String body = productOrder.getDigest();

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    @Transactional
    public void handleState(String out_trade_no, String trade_no) {
        //通过商户订单号获取paybill
        PayBill payBill = payBillMapper.findByOrderSn(out_trade_no);
        //设置支付单号
        payBill.setUnionPaySn(trade_no);
        //设置支付完成时间
        payBill.setUpdateTime(new Date());
        //更改支付状态
        payBill.setState(ConstantPethome.PAYMENT_COMPLETED);
        //数据库更新
        payBillMapper.update(payBill);
        //修改服务订单
        switch (payBill.getBusinessType()){
            case PayConstant.BUSINESSTYPE_ADOPT ://领养订单
                break;
            case PayConstant.BUSINESSTYPE_GOODS: //商品订单
                break;
            case PayConstant.BUSINESSTYPE_PRODUCT://服务订单
                //通过业务键去获取服务
                ProductOrder productOrder = productOrderMapper.findById(payBill.getBusinessKey());
                //更改状态
                productOrder.setState(ConstantPethome.PAYMENT_COMPLETED);
                //添加支付单号
                productOrder.setPaySn(trade_no);
                //添加最后确认时间
                productOrder.setLastConfirmTime(new Date());
                //数据库更新
                productOrderMapper.update(productOrder);
                //根据任务名字移除定时任务
                quartzService.removeJob(PayConstant.BUSINESSTYPE_PRODUCT+productOrder.getOrderSn());
                break;
        }

    }
}
